import request from 'umi-request';
import { Toast } from 'antd-mobile';
import { history } from 'umi';
request.interceptors.request.use((url: any, options: any) => {
  //判断本地session是否有数据，如果有就得到token，并付给请求头
  if (localStorage.getItem('token')) {
    console.log("有token",url);
    
    let c_token: any = localStorage.getItem('token');
    //转换获取到的数据格式，得到里面的token
    const headers = {
      Authorization: c_token,
    };
    return {
      url,
      options: { ...options, headers },
    };
  } else {
    console.log("没有token");
    
    history.push({
      pathname: '/login',
    });
  }
});
request.interceptors.response.use(async (response: any, options: any) => {
  const data = await response.clone().json();
  console.log("判断token是否过期");
  
  // 判断token是否过期
  if (data.status == 400) {
    localStorage.removeItem('token');
    history.push({
      pathname: '/login',
    });
    return response;
  } else {
    return response;
  }
});
